<template>
  <view class="container">
    <view class="form-container">
      <picker mode="selector" :range="deviceTypes" @change="handleDeviceTypeChange">
        <view class="input-label">选择设备类型</view>
        <view class="selected-value">{{ selectedDeviceType }}</view>
      </picker>
      <input v-model="name" type="text" placeholder="输入设备名称" class="text-input" />
      <switch :checked="switchStatus" @change="handleDeviceStatusChange"></switch>
	  <input v-model="openCommand" type="text" placeholder="输入开启设备指令" class="text-input" />
	  <input v-model="closeCommand" type="text" placeholder="输入关闭设备指令" class="text-input" />
      <button @tap="addDevice" class="add-button">添加设备</button>
    </view>
	<view class="table-container">
	      <table>
	        <thead>
	          <tr>
	            <th>ID</th>
	            <th>设备类型</th>
	            <th>设备名称</th>
	            <th>设备状态</th>
	            <th>操作</th>
	          </tr>
	        </thead>
	        <tbody>
	          <tr v-for="(device, index) in devices" :key="index">
	            <td>{{ device.id }}</td>
	            <td>{{ device.type }}</td>
	            <td>{{ device.name }}</td>
	            <td>{{ deviceStatusText(device.switchStatus) }}</td>
	            <td>
	              <button @tap="editDevice(device)">编辑</button>
	              <button @tap="deleteDevice(index)">删除</button>
	            </td>
	          </tr>
	        </tbody>
	      </table>
		  <!-- 使用 v-if 条件渲染，当 showEditModal 为 true 时显示子组件 -->
		      <EditDevice v-if="showEditModal" :deviceData="selectedDevice" @close="closeEditModal"></EditDevice>
	    </view>
	  </view>
  </view>
</template>

<script>
	import EditDevice from '@/pages/management/EditDevice/EditDevice';
	
	export default {
	  components: {
	    EditDevice,
	  },
  data() {
    return {
      deviceTypes: ['设备类型1', '设备类型2', '设备类型3'], // Replace with your actual device types
      selectedDeviceType: '设备类型1',
	  id: '',
      name: '',
      switchStatus: false,
	  showEditModal: false,
	  selectedDevice: null, // 存储选中的设备数据
	  openCommand: '', // Store the value of the open command input
	  closeCommand: '', // Store the value of the close command input
	  devices: [
	          { id: 1, type: '设备类型1', name: '设备1', switchStatus: true },
	          { id: 2, type: '设备类型2', name: '设备2', switchStatus: false },
	          // Add more devices here
		],
    };
  },
 
  mounted() {
  this.getDeviceList();// Fetch initial data
  },
  methods: {
	getDeviceList() {
		uni.request({
		  url: 'http://localhost:7777/devices/list', // 后端接口的URL，用于获取设备数据
		  method: 'GET', // 使用GET方法请求数据
		  success: (res) => {
		    console.log('Data received from backend:', res.data);
		  
		    // 将后端返回的设备数据赋值给devices数组
		    this.devices = res.data;
		  },
		  fail: (error) => {
		    console.error('Failed to fetch data from backend:', error);
		    // 这里可以处理获取数据失败的情况
		  },
		});
	},
	handleOpenCommandChange(event) {
	  this.openCommand = event.target.value;
	},
	handleCloseCommandChange(event) {
	  this.closeCommand = event.target.value;
	},
    handleDeviceTypeChange(event) {
      this.selectedDeviceType = this.deviceTypes[event.detail.value];
    },
    handleDeviceStatusChange(event) {
      this.switchStatus = event.detail.value;
    },
    addDevice() {
      // Check if the name field is empty
      if (!this.name) {
        // Show a frontend notification for invalid operation
        alert('Name cannot be empty. Please provide a valid name.');
        return;
      }
    
      // You can replace the following code with your actual API call to send data to the backend
      const newDeviceData = {
        type: this.selectedDeviceType,
        name: this.name,
        switchStatus: this.switchStatus,
      };
    
      // 发送数据到后端
      uni.request({
        url: "http://localhost:7777/devices/add", // 后端接口的URL
        method: 'POST', // 使用POST方法发送数据
        data: newDeviceData, // 要发送的数据
        header: {
          'Content-Type': 'application/json', // 根据后端接口要求设置合适的Content-Type
        },
        success: (res) => {
          console.log('Data sent successfully:', res.data);
		let obj = res.data;
          // 这里可以处理后端返回的响应
          // Assuming you want to navigate back after adding the device
		  const OpenCommandData = {
		  				  type: "open",
		         deviceId: obj.id,
		         sendOrder: this.openCommand,
		       };
		  			uni.request({
		  				url: 'http://localhost:7777/commands/add', // 第二个后端路由的URL
		  				method: 'POST', // 使用POST方法发送数据
		  				data: OpenCommandData, // 要发送的数据
		  				header: {
		  				  'Content-Type': 'application/json', // 根据后端接口要求设置合适的Content-Type
		  				},
		  				success: (res) => {
		  				  console.log('OpenCommands added successfully:', res.data);
		  				  // 在第二个后端路由执行成功后，你可以根据后端返回的响应进行相应处理
		  				  const CloseCommandData = {
		  						 type: "close",
		  						 deviceId: obj.id,
		  						 sendOrder: this.closeCommand,
		  					   };
		  					uni.request({
		  						url: 'http://localhost:7777/commands/add', // 第二个后端路由的URL
		  								method: 'POST', // 使用POST方法发送数据
		  								data: CloseCommandData, // 要发送的数据
		  								header: {
		  								  'Content-Type': 'application/json', // 根据后端接口要求设置合适的Content-Type
		  								},
		  								success: (res) => {
		  									console.log('CloseCommands added successfully:', res.data);
		  								},
		  								fail: (error) => {
		  									console.log('失败');
		  								},
		  					});
		  				},
		  				fail: (error) => {
		  					console.log('失败');
		  				},
		  			})
          this.getDeviceList()
        },
        fail: (error) => {
          console.error('Failed to send data:', error);
          // 这里可以处理发送失败的情况
        },
      });
    },

	// Method to display the device switchStatus as text
	deviceStatusText(switchStatus) {
	  return switchStatus ? '在线' : '离线';
	},

	// Method to edit a device
	 // editDevice(device) {
	 //      // Navigate to EditDevice.vue and pass the device data as route parameters
	 //      uni.navigateTo({
	 //        url: `/pages/EditDevice.vue?id=${device.id}&name=${device.name}&status=${device.switchStatus}&type=${device.type}`,
	 //      });
	 //    },
	  editDevice(device) {
	        // 点击编辑按钮时触发，将当前数据列传递给子组件，并显示子组件
	        this.selectedDevice = device;
	        this.showEditModal = true;
	      },
	      closeEditModal() {
	        // 关闭子组件的回调函数
	        this.showEditModal = false;
			this.getDeviceList();
	      },

	// Method to delete a device
	deleteDevice(index) {
	  // Assuming you want to delete the device from the devices array
	  const deviceIdToDelete = this.devices[index].id; // 假设设备的唯一标识符为id字段
		uni.request({
		  url: `http://localhost:7777/devices/delete/${deviceIdToDelete}`, // 后端接口的URL，使用设备的ID作为路径参数
		  method: 'DELETE', // 使用DELETE方法删除设备数据
		  success: (res) => {
			console.log('Device deleted successfully:', res.data);
			// 在删除成功后，可以在前端更新视图，以及做一些提示或其他操作
			this.devices.splice(index, 1); // 从前端数据中删除对应设备
		  },
		  fail: (error) => {
			console.error('Failed to delete device:', error);
			// 这里可以处理删除设备失败的情况
		  },
		});
	},
	//	查设备的
	//     // Method to search devices by type, ID, or name
	//     searchDevices(query) {
	//       // Replace the following code with your actual search logic based on the query
	//       // For example, filter the devices based on the provided query
	//       const filteredDevices = this.devices.filter(
	//         (device) =>
	//           device.type.includes(query) ||
	//           device.id.toString().includes(query) ||
	//           device.name.includes(query)
	//       );
	
	//       // Return the filtered devices to display in the table
	//       return filteredDevices;
	//     },
  },
};
</script>

<style>
.container {
  display: flex;
  flex-direction: column; 
  justify-content: center;
  align-items: center;
  
  background-color: #f1f1f1;
}

.form-container {
  width: 80%;
  margin-top: 20px;
  padding: 20px;
  background-color: #fff;
  border-radius: 10px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
}

.input-label {
  font-size: 16px;
  margin-bottom: 5px;
}

.selected-value {
  font-size: 20px;
  color: #007AFF;
}

.text-input {
  width: 90%;
  height: 40px;
  margin: 10px;
  padding: 0 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 16px;
}

.add-button {
  width: 100%;
  height: 40px;
  margin-top: 20px;
  font-size: 16px;
  background-color: #007AFF;
  color: #fff;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.table-container {
  width: 80%;
  margin-top: 30px;
}

table {
  width: 100%;
  border-collapse: collapse;
  border: 1px solid #ddd;
}

th,
td {
  padding: 8px;
  border: 1px solid #ddd;
}

th {
  background-color: #f2f2f2;
}

button {
  font-size: 14px;
  background-color: #007aff;
  color: #fff;
  border: none;
  border-radius: 4px;
  padding: 6px 10px;
  margin-right: 5px;
  cursor: pointer;
}
</style>
